package com.hkts.naturalgas.base.controller;


import com.hkts.naturalgas.base.entity.CalcinationDesulfurizationDenitration;
import com.hkts.naturalgas.base.entity.CalcinationPurifyWetElectricity;
import com.hkts.naturalgas.base.entity.RoastingDust;
import com.hkts.naturalgas.utils.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.omg.CORBA.Object;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.alibaba.fastjson.JSON;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hkts.naturalgas.base.service.ICalcinationPurificationBleachingService;
import com.hkts.naturalgas.base.entity.CalcinationPurificationBleaching;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 煅烧净化脱白
 *
 * @author yck
 * @since 2021-05-31
 */
@RestController
@RequestMapping("/instrumentdata/calcinationPurificationBleaching")
public class CalcinationPurificationBleachingController {
    private final Logger logger = LoggerFactory.getLogger(CalcinationPurificationBleachingController.class);

    @Autowired
    public ICalcinationPurificationBleachingService iCalcinationPurificationBleachingService;

    /**
     * 分页查询数据
     *
     * @param page                             分页信息
     * @param calcinationPurificationBleaching 查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/getCalcinationPurificationBleachingPageList")
    public Result<CustomPage> getHontUserList(Page<CalcinationPurificationBleaching> page, CalcinationPurificationBleaching calcinationPurificationBleaching) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iCalcinationPurificationBleachingService.selectPage(page, calcinationPurificationBleaching)));
    }

    /**
     * 保存和修改公用的
     *
     * @param calcinationPurificationBleaching 传递的实体
     * @return saveOrUpdate
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/calcinationPurificationBleachingSave")
    public Result<Object> calcinationPurificationBleachingSave(CalcinationPurificationBleaching calcinationPurificationBleaching) {
        iCalcinationPurificationBleachingService.saveOrUpdate(calcinationPurificationBleaching);
        return ResultUtil.success("保存成功");
    }

    /**
     * 根据id获取对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/calcinationPurificationBleachingGetById")
    public Result<CalcinationPurificationBleaching> calcinationPurificationBleachingGetById(String id) {
        CalcinationPurificationBleaching byId = iCalcinationPurificationBleachingService.getById(id);
        return ResultUtil.data(byId);
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/calcinationPurificationBleachingDelete")
    public Result<Object> hontUserDelete(String id) {
        iCalcinationPurificationBleachingService.removeById(id);
        return ResultUtil.success("删除成功");
    }

    /**
     * 批量删除对象
     *
     * @param item 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/calcinationPurificationBleachingBatchDelete")
    public Result<Object> deleteBatchIds(String item) {
        List<String> ids = (List<String>) JSON.parse(item);
        iCalcinationPurificationBleachingService.removeByIds(ids);
        return ResultUtil.success("删除成功");
    }
    @GetMapping("/getPageByTime")
    public Result<CustomPage> getPageByTime(Page<CalcinationPurificationBleaching> page, String startDate, String endDate){
        return ResultUtil.data(CustomPageUtils.getCustomPage(iCalcinationPurificationBleachingService.selectPageByTime(page,startDate,endDate)));
    }
    /** 功能描述:
     *  遍历文件 将数据导入数据库
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-02 18:04
     * @Description //TODO
     */
    @PostMapping("/importByFiles")
    public Result<Object> importByFiles(String url) throws Exception {
        File file=new File(url);
        File[] files=file.listFiles();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int i=0;i<files.length;i++){
            File nextfile=  files[i];
            System.out.println(nextfile.getName());
            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(nextfile));
            HSSFSheet sheet = wb.getSheetAt(0);
            List<CalcinationPurificationBleaching> list=new ArrayList<CalcinationPurificationBleaching>(24);
            for (int j=3;j  >= 2&&j<27; j ++) {
                HSSFRow row1 = sheet.getRow(j);
                CalcinationPurificationBleaching bleaching=new CalcinationPurificationBleaching();
                bleaching.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                System.out.println(row1.getCell(0).getDateCellValue());
                Date dateCellValue = row1.getCell(0).getDateCellValue();
                if(dateCellValue==null){
                    continue;
                }
                bleaching.setTime(dateCellValue.toInstant()
                        .atZone( ZoneId.systemDefault() )
                        .toLocalDateTime());
               //煅烧脱白塔出口湿度
                bleaching.setDsjhTe110((float)row1.getCell(10).getNumericCellValue());
              //煅烧脱白塔进口湿度
                bleaching.setDsjhTe103((float)row1.getCell(3).getNumericCellValue());
                //煅烧脱白塔出口温度
                bleaching.setDsjhTe108((float)row1.getCell(8).getNumericCellValue());
                bleaching.setDsjhSidu((float)row1.getCell(21).getNumericCellValue());
                bleaching.setDsjhFancsv((float)row1.getCell(20).getNumericCellValue());
                bleaching.setDsjhFanbsv((float)row1.getCell(19).getNumericCellValue());
                bleaching.setDsjhFanasv((float)row1.getCell(18).getNumericCellValue());
                bleaching.setDsjhFanadl((float)row1.getCell(13).getNumericCellValue());
                bleaching.setDsjhFanbdl((float)row1.getCell(14).getNumericCellValue());
                bleaching.setDsjhFancdl((float)row1.getCell(15).getNumericCellValue());
                list.add(bleaching);
            }
            iCalcinationPurificationBleachingService.importByFiles(list);
        }

        return ResultUtil.success("成功");
    }
    /** 功能描述:
     *  除尘数据处理 每小时内的数据转为每分钟
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-08 10:26
     * @Description //TODO
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/dataHndler")
    @Transactional
    public Result dataHndler() throws ParseException {
        CalcinationPurificationBleaching denitration = new CalcinationPurificationBleaching();
        List<CalcinationPurificationBleaching> roastingDusts = iCalcinationPurificationBleachingService.selectList(denitration);
        List<String> collect = roastingDusts.stream().map(CalcinationPurificationBleaching::getId).collect(Collectors.toList());
        System.out.println("删除数据");
        iCalcinationPurificationBleachingService.deleteAll(collect);
        for(int i=0;i<roastingDusts.size();i++){
            if(i!=roastingDusts.size()-1){
                LocalDateTime time = roastingDusts.get(i).getTime();
                System.out.println(time);
                Date date = Date.from( time.atZone( ZoneId.systemDefault()).toInstant());
                List<LocalDateTime> allHourse = DataHandlerUtils.getAllHourse(date);
                //根据算法得到一个小时内的所有数据
                //煅烧A风机电流
                List<Float> DsjhFanadl = BezierPoint.getData(roastingDusts.get(i).getDsjhFanadl(), roastingDusts.get(i + 1).getDsjhFanadl());
                //煅烧A风机频率
                List<Float> DsjhFanasv = BezierPoint.getData(roastingDusts.get(i).getDsjhFanasv(), roastingDusts.get(i + 1).getDsjhFanasv());
                //煅烧B风机电流
                List<Float> DsjhFanbdl = BezierPoint.getData(roastingDusts.get(i).getDsjhFanbdl(), roastingDusts.get(i + 1).getDsjhFanbdl());
                //煅烧B风机频率
                List<Float> DsjhFanbsv = BezierPoint.getData(roastingDusts.get(i).getDsjhFanbsv(), roastingDusts.get(i + 1).getDsjhFanbsv());

                //煅烧C风机电流
                List<Float> DsjhFancdl = BezierPoint.getData(roastingDusts.get(i).getDsjhFancdl(), roastingDusts.get(i + 1).getDsjhFancdl());
                //煅烧C风机频率
                List<Float> DsjhFancsv = BezierPoint.getData(roastingDusts.get(i).getDsjhFancsv(), roastingDusts.get(i + 1).getDsjhFancsv());
                //煅烧脱白塔进口湿度
                List<Float> DsjhSidu = BezierPoint.getData(roastingDusts.get(i).getDsjhSidu(), roastingDusts.get(i + 1).getDsjhSidu());
                //煅烧脱白塔进口温度
                List<Float> DsjhTe103 = BezierPoint.getData(roastingDusts.get(i).getDsjhTe103(), roastingDusts.get(i + 1).getDsjhTe103());
                //煅烧脱白塔出口温度
                List<Float> DsjhTe108 = BezierPoint.getData(roastingDusts.get(i).getDsjhTe108(), roastingDusts.get(i + 1).getDsjhTe108());
                //煅烧脱白塔出口湿度
                List<Float> DsjhTe110 = BezierPoint.getData(roastingDusts.get(i).getDsjhTe110(), roastingDusts.get(i + 1).getDsjhTe110());

                //进行循环处理
                List<CalcinationPurificationBleaching> list=new ArrayList<CalcinationPurificationBleaching>();
                for(int j=0;j<DsjhFanadl.size();j++){
                    if (j==0){
                        roastingDusts.get(i).setDsjhFanadl(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getDsjhFanadl()));
                        roastingDusts.get(i).setDsjhFanasv(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getDsjhFanasv()));
                        roastingDusts.get(i).setDsjhFanbdl(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getDsjhFanasv()));
                        roastingDusts.get(i).setDsjhFanbsv(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getDsjhFanasv()));
                        roastingDusts.get(i).setDsjhFancdl(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getDsjhFanasv()));
                        roastingDusts.get(i).setDsjhFancsv(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getDsjhFanasv()));
                        roastingDusts.get(i).setDsjhSidu(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getDsjhFanasv()));
                        roastingDusts.get(i).setDsjhTe103(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getDsjhFanasv()));
                        roastingDusts.get(i).setDsjhTe108(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getDsjhFanasv()));
                        roastingDusts.get(i).setDsjhTe110(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getDsjhFanasv()));
                        roastingDusts.get(i).setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                        list.add(roastingDusts.get(i));
                    }else {
                        CalcinationPurificationBleaching calcinationPurificationBleaching = new CalcinationPurificationBleaching();
                        calcinationPurificationBleaching.setDsjhFanadl(DsjhFanadl.get(j));
                        calcinationPurificationBleaching.setDsjhFanasv(DsjhFanasv.get(j));
                        calcinationPurificationBleaching.setDsjhFanbdl(DsjhFanbdl.get(j));
                        calcinationPurificationBleaching.setDsjhFanbsv(DsjhFanbsv.get(j));
                        calcinationPurificationBleaching.setDsjhFancdl(DsjhFancdl.get(j));
                        calcinationPurificationBleaching.setDsjhFancsv(DsjhFancsv.get(j));
                        calcinationPurificationBleaching.setDsjhSidu(DsjhSidu.get(j));
                        calcinationPurificationBleaching.setDsjhTe103(DsjhTe103.get(j));
                        calcinationPurificationBleaching.setDsjhTe108(DsjhTe108.get(j));
                        calcinationPurificationBleaching.setDsjhTe110(DsjhTe110.get(j));
                        calcinationPurificationBleaching.setTime(allHourse.get(j));
                        calcinationPurificationBleaching.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                        list.add(calcinationPurificationBleaching);
                    }

                }
                iCalcinationPurificationBleachingService.saveBatch(list);
            }else{
                iCalcinationPurificationBleachingService.save(roastingDusts.get(i));
            }
        }
        return ResultUtil.success("处理成功！");
    }
    /** 功能描述:
     *  遍历文件 将数据导入数据库
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-02 18:04
     * @Description //TODO
     */
    @PostMapping("/importByFilesJun")
    public Result<Object> importByFilesJun(String url) throws Exception {
        File file=new File(url);
        HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
        HSSFSheet sheet = wb.getSheetAt(0);
        List<CalcinationPurificationBleaching> list=new ArrayList<CalcinationPurificationBleaching>(24);
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i ++) {
            HSSFRow row1 = sheet.getRow(i);
            CalcinationPurificationBleaching bleaching=new CalcinationPurificationBleaching();
            bleaching.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
            System.out.println(row1.getCell(0).getDateCellValue());
            Date dateCellValue = row1.getCell(0).getDateCellValue();
            if(dateCellValue==null){
                continue;
            }
            bleaching.setTime(dateCellValue.toInstant()
                    .atZone( ZoneId.systemDefault() )
                    .toLocalDateTime());
            //焙烧一电场二次电流
            bleaching.setDsjhFanadl((float)row1.getCell(1).getNumericCellValue());
            //焙烧一电场二次电压
            bleaching.setDsjhFanasv((float)row1.getCell(2).getNumericCellValue());
            //焙烧二电场二次电流
            bleaching.setDsjhFanbdl((float)row1.getCell(3).getNumericCellValue());
            //焙烧二电场二次电压
            bleaching.setDsjhFanbsv((float)row1.getCell(4).getNumericCellValue());
            bleaching.setDsjhFancdl((float)row1.getCell(5).getNumericCellValue());
            bleaching.setDsjhFancsv((float)row1.getCell(6).getNumericCellValue());
            bleaching.setDsjhSidu((float)row1.getCell(7).getNumericCellValue());
            bleaching.setDsjhTe103((float)row1.getCell(8).getNumericCellValue());
            bleaching.setDsjhTe108((float)row1.getCell(9).getNumericCellValue());
            bleaching.setDsjhTe110((float)row1.getCell(9).getNumericCellValue());
            list.add(bleaching);
        }
        iCalcinationPurificationBleachingService.saveBatch(list);

        return ResultUtil.success("成功");
    }

    /** 功能描述:
     *  遍历文件 将数据导入数据库
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-02 18:04
     * @Description //TODO
     */
    @PostMapping("/updateByFiles")
    @Transactional
    public Result<Object> updateByFiles(String url) throws Exception {
        File file=new File(url);
        File[] files=file.listFiles();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("size:"+files.length);
        for(int i=0;i<files.length;i++){
            File nextfile=  files[i];
            System.out.println(nextfile.getName());
            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(nextfile));
            HSSFSheet sheet = wb.getSheetAt(0);
            List<CalcinationPurificationBleaching> list=new ArrayList<CalcinationPurificationBleaching>(24);
            for (int j=3;j  >= 2&&j<27; j ++) {
                HSSFRow row1 = sheet.getRow(j);
                if(j==3){
                    System.out.println(row1.getCell(0).getDateCellValue());
                }
                Date dateCellValue = row1.getCell(0).getDateCellValue();
                if(dateCellValue==null){
                    continue;
                }
                //通过日期去查询
                CalcinationPurificationBleaching bleaching= iCalcinationPurificationBleachingService.selectByTime(dateCellValue.toInstant()
                        .atZone( ZoneId.systemDefault() )
                        .toLocalDateTime());
               if(bleaching==null){
                   bleaching=new CalcinationPurificationBleaching();
                   bleaching.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                   bleaching.setTime(dateCellValue.toInstant()
                           .atZone( ZoneId.systemDefault() )
                           .toLocalDateTime());
               }

                //煅烧脱白塔出口湿度
                bleaching.setDsjhTe110((float)row1.getCell(10).getNumericCellValue());
                //煅烧脱白塔进口湿度
                bleaching.setDsjhTe103((float)row1.getCell(3).getNumericCellValue());
                //煅烧脱白塔出口温度
                bleaching.setDsjhTe108((float)row1.getCell(8).getNumericCellValue());
                bleaching.setDsjhSidu((float)row1.getCell(21).getNumericCellValue());
                bleaching.setDsjhFancsv((float)row1.getCell(20).getNumericCellValue());
                bleaching.setDsjhFanbsv((float)row1.getCell(19).getNumericCellValue());
                bleaching.setDsjhFanasv((float)row1.getCell(18).getNumericCellValue());
                bleaching.setDsjhFanadl((float)row1.getCell(13).getNumericCellValue());
                bleaching.setDsjhFanbdl((float)row1.getCell(14).getNumericCellValue());
                bleaching.setDsjhFancdl((float)row1.getCell(15).getNumericCellValue());
                list.add(bleaching);
            }
           iCalcinationPurificationBleachingService.saveOrUpdateBatch(list);
        }
        return ResultUtil.success("成功");
    }
    /** 功能描述:
    *
    * @return:
    * @Author: 杨春科
    * @Date: 2021-06-14 13:18
    * @Description //TODO
    */
    @PostMapping("/dataHandleByFiles")
    @Transactional
    public Result<Object> dataHandleByFiles(String url) throws Exception {
        File file=new File(url);
        File[] files=file.listFiles();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("size:"+files.length);
        List<LocalDateTime> list=new ArrayList<LocalDateTime>(24);

        for(int i=0;i<files.length;i++){
            File nextfile=  files[i];
            System.out.println(nextfile.getName());
            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(nextfile));
            HSSFSheet sheet = wb.getSheetAt(0);

            for (int j=3;j  >= 2&&j<27; j ++) {
                HSSFRow row1 = sheet.getRow(j);
                Date dateCellValue = row1.getCell(0).getDateCellValue();
                if(dateCellValue==null){
                    continue;
                }
                //通过日期去查询
                list.add(dateCellValue.toInstant()
                        .atZone( ZoneId.systemDefault() )
                        .toLocalDateTime());
            }
        }
        List<LocalDateTime> collect = list.stream().sorted().collect(Collectors.toList());

        for(int i=0;i<collect.size();i++){
            if(i!=collect.size()-1){
             List<CalcinationPurificationBleaching> cls=iCalcinationPurificationBleachingService.selectByTimes(collect.get(i),collect.get(i+1));
                System.out.println(cls.get(0).getTime());
                for(int j=1;j<cls.size();j++){
                    cls.get(j).setDsjhFancsv(cls.get(0).getDsjhFanasv());
                    cls.get(j).setDsjhFancdl(DataHandlerUtils.electricDataHandler(cls.get(0).getDsjhFancdl()));
                    cls.get(j).setDsjhFanbsv(cls.get(0).getDsjhFanbsv());
                    cls.get(j).setDsjhFanadl( DataHandlerUtils.electricDataHandler(cls.get(0).getDsjhFanadl()));
                    cls.get(j).setDsjhSidu(cls.get(0).getDsjhSidu());
                    cls.get(j).setDsjhTe103(cls.get(0).getDsjhTe103());
                    cls.get(j).setDsjhTe108(cls.get(0).getDsjhTe108());
                    cls.get(j).setDsjhTe110(cls.get(0).getDsjhTe110());
                    cls.get(j).setDsjhFancsv(cls.get(0).getDsjhFancsv());
                    cls.get(j).setDsjhFancdl(DataHandlerUtils.electricDataHandler(cls.get(0).getDsjhFanadl()));
                }
              iCalcinationPurificationBleachingService.saveOrUpdateBatch(cls);
            }
        }
        return ResultUtil.success("成功");
    }
    /** 功能描述:
     *根据时间将数据补全 所有值全为0
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-17 10:49
     * @Description //TODO
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/addData")
    @Transactional
    public Result<java.lang.Object> addData(String beginDate, String endDate) throws ParseException {
        List<LocalDateTime> allMinites = DataHandlerUtils.getAllMinites(beginDate, endDate);
        List<CalcinationPurificationBleaching> calcinationPurificationBleachings =new ArrayList<CalcinationPurificationBleaching>();
        for(int i=0;i<allMinites.size();i++){
            CalcinationPurificationBleaching den=new CalcinationPurificationBleaching();
            den.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
            den.setTime(allMinites.get(i));
            den.setDsjhFancdl(0f);
            den.setDsjhFancsv(0f);
            den.setDsjhTe110(0f);
            den.setDsjhTe108(0f);
            den.setDsjhTe103(0f);
            den.setDsjhSidu(0f);
            den.setDsjhFanadl(0f);
            den.setDsjhFanbdl(0f);
            den.setDsjhFanasv(0f);
            den.setDsjhFanbsv(0f);
            calcinationPurificationBleachings.add(den);
        }
        iCalcinationPurificationBleachingService.saveBatch(calcinationPurificationBleachings);
        return ResultUtil.success("处理成功！");
    }
}
